<template>
  <div>
    <div style="margin-bottom: 30px">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>人员信息管理</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <div style="margin: 10px 0">
      <el-input style="width: 200px" placeholder="请输入姓名"
                v-model="name" suffix-icon="el-icon-search"></el-input>
      <el-input style="width: 200px" placeholder="请输入用户名"
                v-model="username" suffix-icon="el-icon-user" class="ml-5 mr-5"></el-input>
      <template>
        <el-select v-model="gender" placeholder="请选择性别">
          <el-option label="全部" value=" "></el-option>
          <el-option label="男" value="男"></el-option>
          <el-option label="女" value="女"></el-option>
        </el-select>
      </template>
      <el-button class="ml-5" type="primary" @click="search">搜索</el-button>
      <el-button class="ml-5" type="warning" @click="reset">重置</el-button>
    </div>

    <div style="margin: 10px 0">
      <el-button type="primary" @click="handleAdd" class="mr-5">新增 <i class="el-icon-circle-plus-outline"></i>
      </el-button>
      <el-popconfirm
          confirm-button-text='确定'
          cancel-button-text='再想想'
          icon="el-icon-info"
          icon-color="red"
          title="确定批量删除吗？"
          @confirm="delBatch">
        <el-button type="danger" slot="reference" class="mr-5">批量删除 <i class="el-icon-remove-outline"></i></el-button>
      </el-popconfirm>
    </div>
    <el-table :data="tableData" border stripe
              @selection-change="handleSelectionChange">
      <el-table-column
          type="selection"
          width="40">
      </el-table-column>
      <el-table-column prop="staffId" label="id" width="40">
      </el-table-column>
      <el-table-column prop="address" label="地址" width="80">
      </el-table-column>
      <el-table-column prop="staffName" label="账号" width="80">
      </el-table-column>
      <el-table-column prop="trueName" label="真实姓名" width="70">
      </el-table-column>
      <el-table-column prop="phoneNumber" label="电话号码" width="80">
      </el-table-column>

      <el-table-column prop="gender" label="性别" width="50">
        <template slot-scope="scope">
          {{scope.row.gender | showGender}}
        </template>
      </el-table-column>
      <el-table-column prop="idNumber" label="身份证号" width="100">
      </el-table-column>
      <el-table-column prop="born" label="生日" width="120">
      </el-table-column>
      <el-table-column prop="" label="头像" width="75" align="center">
        <template slot-scope="scope">
          <el-avatar :src="scope.row.photo" alt="" style="width: 50px;height: 50px"></el-avatar>
        </template>
      </el-table-column>
      <el-table-column prop="bank" label="开户银行" width="70">
      </el-table-column>
      <el-table-column prop="bankNumber" label="银行卡号" width="100">
      </el-table-column>
      <el-table-column prop="character" label="工作性质" width="50">
      </el-table-column>
      <el-table-column prop="stats" label="状态" width="60">
      </el-table-column>
      <el-table-column label="操作" width="" align="center">
        <template slot-scope="scope">
          <el-button type="success" @click="handleEdit(scope.row)" class="mr-5">
            查看<i class="el-icon-edit"></i>
          </el-button>
          <el-popconfirm
              confirm-button-text='确定'
              cancel-button-text='再想想'
              icon="el-icon-info"
              icon-color="red"
              title="确定删除吗？"
              @confirm="del(scope.row.staffId)">
            <el-button type="danger" slot="reference">删除 <i class="el-icon-remove-outline"></i></el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <div style="padding: 10px 0">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :page-sizes="[5, 10, 15, 20]"
          :page-size=pageSize
          layout="total, sizes, prev, pager, next, jumper"
          :total=total>
      </el-pagination>
    </div>
    <!--    人员信息的弹窗    -->
    <el-dialog title="详细信息" :visible.sync="dialogFormVisible" width="50%" :close-on-click-modal="false">
      <el-form :model="staff" :inline="true" :rules="rules" ref="staff">
        <el-form-item label="员工账号" label-width="100px" prop="staffName">
          <el-input v-model="staff.staffName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" label-width="100px" prop="password">
          <el-input v-model="staff.password" autocomplete="off" type="password"></el-input>
        </el-form-item>
        <el-form-item label="姓名" label-width="100px" prop="trueName">
          <el-input v-model="staff.trueName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="电话" label-width="100px" prop="phoneNumber">
          <el-input v-model="staff.phoneNumber" autocomplete="off" type="number"></el-input>
        </el-form-item>
        <el-form-item label="部门" label-width="100px" prop="departmentId">
          <el-select v-model="staff.departmentId" placeholder="请选择部门" style="width: 185px">
            <el-option
                v-for="dep in deps"
                :key="dep.deptId"
                :label="dep.deptName"
                :value="dep.deptId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="权限" label-width="100px" prop="power">
          <template>
            <el-radio v-model="staff.power" label="1">部门管理员</el-radio>
            <el-radio v-model="staff.power" label="0">员工</el-radio>
          </template>
        </el-form-item>
        <el-form-item label="身份证号" label-width="100px" prop="idNumber">
          <el-input v-model="staff.idNumber" autocomplete="off" type="number"></el-input>
        </el-form-item>
        <el-form-item label="地址" label-width="100px" prop="address">
          <el-cascader
              style="width: 185px"
              :options="options"
              v-model="areaCodes"
              @change="getArea">
          </el-cascader>
        </el-form-item>
        <el-form-item label="文化程度" label-width="100px" prop="education">
          <el-input v-model="staff.education" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="性别" label-width="100px" prop="gender">
          <template>
            <el-radio v-model="staff.gender" label="1">男</el-radio>
            <el-radio v-model="staff.gender" label="0">女</el-radio>
          </template>
        </el-form-item>
        <el-form-item label="政治面貌" label-width="100px" prop="polity">
          <el-input v-model="staff.polity" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="参加工作时间" label-width="100px" prop="workDate">
          <el-date-picker type="date" placeholder="选择日期" v-model="staff.workDate" style="width: 185px;"></el-date-picker>
        </el-form-item>
        <el-form-item label="出生日期" label-width="100px" prop="born">
          <el-date-picker type="date" placeholder="选择日期" v-model="staff.born" style="width: 185px;"></el-date-picker>
        </el-form-item>
        <el-form-item label="开户银行" label-width="100px" prop="bank">
          <el-input v-model="staff.bank" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="银行卡号" label-width="100px" prop="bankNumber">
          <el-input v-model="staff.bankNumber" autocomplete="off" type="number"></el-input>
        </el-form-item>
        <el-form-item label="工作性质" label-width="100px" prop="character">
          <el-input v-model="staff.character" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="状态" label-width="100px" prop="stats">
          <el-input v-model="staff.stats" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="头像" label-width="100px" prop="">
          <el-upload
              class="avatar-uploader"
              action="http://localhost/file/upload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess1"
              :before-upload="beforeAvatarUpload">
            <img v-if="staff.photo" :src="staff.photo" class="avatar" alt="">
            <img v-else-if="avatarUrl" :src="avatarUrl" class="avatar" alt="">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>

        <el-form-item label="身份证扫描件正面" label-width="100px" prop="">
          <el-upload
              class="avatar-uploader"
              action="http://localhost/file/upload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess2"
              :before-upload="beforeAvatarUpload">
            <img v-if="staff.idPicture" :src="staff.idPicture" class="avatar" alt="">
            <img v-else-if="idPicUrl" :src="idPicUrl" class="avatar" alt="">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>

        <el-form-item label="身份证扫描件背面" label-width="100px" prop="">
          <el-upload
              class="avatar-uploader"
              action="http://localhost/file/upload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess3"
              :before-upload="beforeAvatarUpload">
            <img v-if="staff.idPictureBack" :src="staff.idPictureBack" class="avatar" alt="">
            <img v-else-if="idPicBackUrl" :src="idPicBackUrl" class="avatar" alt="">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible=false">取 消</el-button>
        <el-button type="primary" @click="save('staff')">{{ btnText }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {  regionData,CodeToText,TextToCode } from 'element-china-area-data'
import request from "@/utils/request";
import Area from "@/components/Area";
// import {TextToCode} from "element-china-area-data/dist/app";

export default {
  name: "Staff",
  components:{Area},
  data() {
    return {
      tableData: [],
      currentPage: 1,
      name: "",
      username: "",
      gender: "",
      pageSize: 5,
      total: 0,
      dialogFormVisible: false,
      btnText: "",
      staff: {},
      multipleSelection: [],
      avatarUrl: '',
      idPicUrl:'',
      idPicBackUrl:'',
      areaCodes:[],
      isEditingArea:false,
      options: regionData,
      deps:[],
      rules: {
        password: [
          {required: true, message: '请填写该字段', trigger: 'blur'},
        ],
        // gender: [
        //   {required: true, message: '请选择性别', trigger: 'blur'},
        // ],
        phoneNumber: [
          {required: true, message: '请输入电话号码', trigger: 'blur'},
          {min: 11, max: 11, message: '请输入长度为11个数字的电话号码', trigger: 'blur'}
        ],
      },
    }
  },
  created() {
    this.load()
    request.get('dept').then(res=>{
      this.deps=res.data
    })
  },
  filters:{
    showGender(gender){
      if (gender===0){
        return '女'
      }else {
        return '男'
      }
    }
  },
  methods: {
    load() {
      request.get("/staff/get",
          {params: {pageNum: this.currentPage, pageSize: this.pageSize}}
      ).then(res => {
        this.tableData = res.data.records
        this.total = res.data.total
        this.currentPage = res.data.current
        this.pageSize = res.data.size
      })
    },
    handleSizeChange(pageSize) {
      this.pageSize = pageSize
      this.load()
    },
    handleCurrentChange(pageNum) {
      this.currentPage = pageNum
      this.load()
    },
    handleAdd() {
      this.areaCodes = []
      this.btnText = "添加"
      this.isEditingArea=true
      this.staff = {}
      this.dialogFormVisible = true
    },
    handleEdit(row) {
      this.areaCodes = []
      this.btnText = "修改"
      this.isEditingArea=false
      this.dialogFormVisible = true
      this.staff = Object.assign({}, row)
      let areaNames=this.staff.address.split('/')
      console.log(this.areaCodes)
      this.areaCodes[0]=TextToCode[areaNames[0]].code
      this.areaCodes[1]=TextToCode[areaNames[0]][areaNames[1]].code
      this.areaCodes[2]=TextToCode[areaNames[0]][areaNames[1]][areaNames[2]].code
    },
    save(staff) {
      this.$refs[staff].validate((valid) => {
        if (valid) {
          this.dialogFormVisible = false
          if (this.btnText==='添加'){

            // this.areatoString(this.staff.address)
            request.post("staff/add", this.staff).then(res => {
              if (res) {
                this.$message.success(this.btnText + "成功")
                this.load()
                this.avatarUrl = ""
                this.idPicUrl = ""
                this.idPicBackUrl = ""
              } else {
                this.$message.error(this.btnText + "失败")
              }
            })
          }else{
            console.log(this.staff.address)
            // this.areatoString(this.staff.address)
            request.put("staff/update", this.staff).then(res => {
              if (res) {
                this.$message.success(this.btnText + "成功")
                this.load()
                this.avatarUrl = ""
                this.idPicUrl = ""
                this.idPicBackUrl = ""
              } else {
                this.$message.error(this.btnText + "失败")
              }
            })
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    del(id) {
      request.delete("staff/delmore/" + id).then(res => {
        if (res.code === 200) {
          this.$message.success("删除成功")
          this.load()
        } else {
          this.$message.error("删除失败")
        }
      })
      console.log(id)
    },
    handleSelectionChange(val) {
      // console.log(val)
      this.multipleSelection = val
    },
    delBatch() {
      //map函数：数组的每个元素都执行一个给定的函数，返回值仍为一个数组
      let ids = this.multipleSelection.map(v => v.staffId)
      console.log(ids)
      if (ids.length !== 0) {
        request.delete("staff/delmore/"+ids.toString(), ).then(res => {
          if (res) {
            this.$message.success("批量删除成功")
            this.load()
          } else {
            this.$message.error("批量删除失败")
          }
        })
      } else {
        this.$message.warning("请选择要删除的数据")
      }
    },
    search() {
      if (this.gender === " ") {
        this.gender = ""
      }
      request.get("/staff/selectbycondition", {
        params: {
          name: this.name,
          username: this.username,
          gender: this.gender,
        }
      }).then(res => {
        this.tableData = res
        this.total = this.tableData.length
        this.currentPage = 0
      })
    },
    reset() {
      this.username = ""
      this.name = ""
      this.gender = ""
      this.load()
    },
    getArea(area){
      this.staff.address=this.areatoString(area)
      console.log(area)
    },
    areatoString(value){
        let dz = CodeToText[value[0]] + '/' + CodeToText[value[1]] + '/' + CodeToText[value[2]]
        return dz
    },
    handleAvatarSuccess1(res, file) {//处理头像
      this.avatarUrl = URL.createObjectURL(file.raw);
      this.staff.photo = res
    },
    handleAvatarSuccess2(res, file) {//处理身份证正面
      this.idPicUrl = URL.createObjectURL(file.raw);
      this.staff.idPicture = res
    },
    handleAvatarSuccess3(res, file) {//处理身份证背面
      this.idPicBackUrl = URL.createObjectURL(file.raw);
      this.staff.idPictureBack = res
    },
    beforeAvatarUpload(file) {
      const isJPG_PNG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG_PNG) {
        this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG_PNG && isLt2M;
    }
  }
}
</script>

<style scoped>
.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
}

.avatar-uploader:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>